Kechin001.PanelReceipt = Ext.extend(Ext.Panel, {
  constructor: function(config) {
    var me = this;

    config.title = 'Receipt';
    config.layout = 'card';
    config.height = 500;
    config.activeItem = 0;
    config.bodyStyle = 'padding:15px';
    config.defaults = { border: false };

    var cardInput = {
      id: 'panel-receipt-input',
      height: 300,
      items: [{
        // title and navigator button
        xtype: 'panel',
        layout: 'hbox',
        align: 'stretch',
        pack: 'end',
        border: false,
        height: 40,
        width: 320,
        items: [{
          xtype: 'box',
          autoEl: 'h2',
          html: 'Enter a receipt',
          flex: 1,
          style: 'text-align:center'
        },{
          xtype: 'button',
          text: '&gt;',
          width: 22,
          tooltip: { text: '<b>Roll to list all receipt</b>', showDelay: 100 },
          handler: function() {
            me.getLayout().setActiveItem('panel-receipt-list');
          }
        }]
      },{
        // the form
        id: 'form-receipt',
        xtype: 'form',
        layout: 'form',
        url: '/save',
        cls: 'frame-panel',
        padding: '20 30 20 30',
        width: 325,
        labelWidth: 80,
        defaults: {
          width: 170
        },
        items: [{
          id: 'id',
          name: 'id',
          xtype: 'hidden'
        },{
          id: 'subject',
          name: 'subject',
          xtype: 'combo',
          fieldLabel: 'Subject',
          store: new Ext.data.JsonStore({
            autoDestroy: true,
            url: '/subject',
            fields: ['name'],
            root: 'resultSet'
          }),
          displayField: 'name',
          typeAhead: true,
          mode: 'local',
          triggerAction: 'all',
          emptyText: 'Enter or select...',
          allowBlank: false,
          listeners: { focus: function(me) { me.getStore().load(); } }
        },{
          id: 'category',
          name: 'category',
          xtype: 'combo',
          fieldLabel: 'Category',
          store: new Ext.data.JsonStore({
            autoDestroy: true,
            url: '/category',
            fields: ['name'],
            root: 'resultSet'
          }),
          displayField: 'name',
          typeAhead: true,
          mode: 'local',
          triggerAction: 'all',
          emptyText: 'Enter or select...',
          allowBlank: false,
          listeners: { focus: function(me) { me.getStore().load(); } }
        },{
          xtype: 'compositefield',
          fieldLabel: 'Amount',
          items: [{
            id: 'currency',
            name: 'currency',
            hiddenName: 'currency', //it then sends valueField instead of displayField
            xtype: 'combo',
            mode: 'local',
            store: new Ext.data.ArrayStore({
              fields: ['display', 'value'],
              data : [['$(USD)', 'USD'], ['$(CND)', 'CND'], ['￥(RMB)', 'RMB']]
            }),
            displayField: 'display',
            valueField: 'value',
            editable: false,
            forceSelection: true,
            triggerAction: 'all',
            width: 75,
            value: 'USD',
            allowBlank: false
          },{
            id: 'amount',
            name: 'amount',
            xtype: 'numberfield',
            width: 90,
            allowBlank: false
          }]
        },{
          id: 'date',
          name: 'date',
          xtype: 'datefield',
          format: 'Y-m-d',
          fieldLabel: 'Date',
          width: 170,
          allowBlank: false,
          emptyText: 'yyyy-mm-dd'
        },{
          xtype: 'button',
          text: 'save',
          width: 75,
          bindForm: true,
          style: 'margin: 15 0 0 180',
          handler: function(){
            Ext.getCmp('form-receipt').getEl().mask('Submitting...', 'x-mask-loading');
            Ext.getCmp('form-receipt').getForm().submit({
              clientValidation: true,
              success: function(form, action){
                Ext.getCmp('form-receipt').getEl().unmask();
                Kechin001.MsgGreen(action.result.msg);
                form.reset();
              },
              failure: function(form, action){
                Ext.getCmp('form-receipt').getEl().unmask();
                Kechin001.MsgRed(action.result.msg);
              }
            });
          }
        }]
      }]
    };

    var cardList = {
      id: 'panel-receipt-list',
      items: [{
        // title and navigator button
        xtype: 'panel',
        layout: 'hbox',
        align: 'stretch',
        pack: 'start',
        border: false,
        height: 40,
        width: 440,
        items: [{
          xtype: 'button',
          text: '&lt;',
          width: 22,
          tooltip: '<b>Roll to enter a new receipt</b>',
          handler: function() {
            me.getLayout().setActiveItem('panel-receipt-input');
          }
        },{
          xtype: 'box',
          autoEl: 'h2',
          html: 'List',
          flex: 1,
          style: 'text-align:center'
        }]
      },{
        xtype: 'grid',
        id: 'grid-receipt-list',
        cls: 'frame-panel',
        height: 400,
        width: 440,
        loadMask: true,
        colModel: new Ext.grid.ColumnModel({
          defaults: {
            menuDisabled: true
          },
          columns: [{
            header: 'Date', dataIndex: 'Date', width:50, xtype:'datecolumn', format:'m/d'
          },{
            header: 'Subject', dataIndex: 'Subject', width:140, renderer: function(value, meta, record, index) {
              return String.format('<a href="#" onclick="Ext.getCmp(\'panel-receipt-list\').edtClicked({0});">{1}</a>', index, value);
            }
          },{
            header: 'Category', dataIndex: 'Category', width:80
          },{
            header: 'Currency', dataIndex: 'Currency', width:60
          },{
            header: 'Amount', dataIndex: 'Amount', width:60, renderer: function(value) {
              return Ext.util.Format.number(value, '0.00');
            }
          },{
            header: '', width:40, renderer: function(value, meta, record, index) { 
              return String.format('[<a href="#" onclick="Ext.getCmp(\'panel-receipt-list\').delClicked({0});">x</a>]', index); 
            }
          }]
        }),
        store: new Ext.data.JsonStore({
          url: '/list',
          storeId: 'receipts',
          root: 'resultSet',
          totalProperty: 'count',
          fields: [
            {name:'Date', type:'date', dateFormat:'Y-m-d'},
            'Subject',
            'Category', 
            'Currency',
            {name:'Amount', type:'float'},
            'Id'
          ]
        })
      }],
      listeners: {
        activate: function(){
          Ext.getCmp('grid-receipt-list').getStore().load();
        }
      },
      edtClicked: function(index){
        record = Ext.getCmp('grid-receipt-list').getStore().getAt(index);

        Ext.getCmp('id').setValue(record.data['Id']);
        Ext.getCmp('date').setValue(record.data['Date']);
        Ext.getCmp('subject').setValue(record.data['Subject']);
        Ext.getCmp('category').setValue(record.data['Category']);
        Ext.getCmp('currency').setValue(record.data['Currency']);
        Ext.getCmp('amount').setValue(record.data['Amount']);

        me.getLayout().setActiveItem('panel-receipt-input');
      },
      delClicked: function(index){
        record = Ext.getCmp('grid-receipt-list').getStore().getAt(index);
        Ext.Msg.confirm('',
          String.format('Delete the following receipt?<br/>{0} {1} {2}', record.data['Date'].format('m/d'), record.data['Subject'], Ext.util.Format.number(record.data['Amount'], '0.00')),
          function(button){
            if(button == 'yes'){
              Ext.getCmp('grid-receipt-list').getEl().mask('Submitting...', 'x-mask-loading');
              // send request to delete the given record
              Ext.Ajax.request({
                url: '/del',
                params: {id: record.data['Id']},
                method: 'POST',
                success: function(response, opts){
                  Ext.getCmp('grid-receipt-list').getEl().unmask();
                  var result = Ext.decode(response.responseText);
                  if(result.success){
                    Kechin001.MsgGreen('Receipt deleted.');
                    Ext.getCmp('grid-receipt-list').getStore().remove(record);
                  }else{
                    Kechin001.MsgRed(result.msg);
                  }
                },
                failure: function(response, opts){
                  Ext.getCmp('grid-receipt-list').getEl().unmask();
                  Kechin001.MsgRed('Error: ' + response.status);
                }
              });
            }
          }
        );
      }
    };

    config.items = [ cardInput, cardList ];

    Kechin001.PanelReceipt.superclass.constructor.call(this, config);
  }
});
Ext.reg('kechin001PanelReceipt', Kechin001.PanelReceipt);
